from mysql_utils import *
from redis_utils import *

import jieba


# 导入常见符号和非关键词
with open('common_symbol.txt', 'r', encoding='utf-8') as f:
    common_symbols = set([line.strip() for line in f.readlines()])

with open('not_keyword.txt', 'r', encoding='utf-8') as f:
    not_keyword = set([line.strip() for line in f.readlines()])


# 载入自定义词典
jieba.load_userdict("userdict.txt")


def get_mysql_link(word):
    """
    @summary: 在mysql查找并返回
    @param key: 词
    @return: 有，返回词的链接；无，返回空子符
    """
    mysql = MyPymysqlPool('dbMysql')
    query = 'SELECT link FROM keywords WHERE keyword=%s'
    link = mysql.getOne(query, word)
    mysql.dispose()
    return link['link'] if link else ''

def get_redis_link(word):
    """
    @summary: 在redis中查找并返回
    @param word: 词
    @return: 有，返回词的链接，无，返回空
    """
    opr = OPRedis()
    return opr.getRedis(word)

def is_skip_search(word):
    """
    @summary: 跳过常见符号和非关键词
    @param word: 词
    @return: 在“常见符号”和“非关键词”中，返回True；否则返回False
    """
    if word in common_symbols and word in not_keyword:
        return True
    else:
        return False
    

def not_replace(words, start_index):
    """
    @summary: 遇到"["开头的，判断是否满足 "[词](任意符号)" 格式
    @param words: 分词列表
    @param start_index: "["处的索引值
    @return: 满足，返回 ")"处的索引值加1；不满足，返加 "[" 处的索引值加1
    """
    end_index = len(words) - 1
    temp_index = start_index + 1

    while temp_index <= end_index and words[temp_index] != "]" and words[temp_index+1] !="(":
        temp_index += 1
    
    temp_index += 2

    while temp_index <= end_index:
        if (words[temp_index] == ")"):
            return temp_index
        temp_index += 1

    return start_index+1


def replace_keyword_with_link(word):
    """
    @param word: 词
    @return: 有链接，[词](链接)；无链接，不更改
    """
    link = get_redis_link(word) if get_redis_link(word) else get_mysql_link(word)

    if link:
        return f'[{word}]({link})'
    else:
        return word


def replace_text(text):
    """
    @summary: 将关键词替换成带链接的关键词
    @param text: 文本
    @return: [文本](链接)
    """
    words = list(jieba.cut(text, cut_all=False))

    i = 0
    while i < len(words):
        # 若明显不是关键词，跳过
        if is_skip_search(words[i]):
            i += 1
            continue
        # 若满足[词](链接)格式，跳过
        if words[i] == "[":
            i = not_replace(words, i) 
        
        # 查询，是关键词，改为[关键词](链接)；不是关键词，不更改
        words[i] = replace_keyword_with_link(words[i])
        i += 1

    return ''.join(words)



def run_app(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as f_input, open(output_file, 'w', encoding='utf-8') as f_output:
        # 避免一次文本过大，逐行处理文本
        for line in f_input:
            words = replace_text(line)
            f_output.write(''.join(words))


if __name__ == '__main__':
    run_app('input.md', 'output.md')